/**
 * 主页 初始化js
 */

function makeGlobalLayer(title, divId) {
	layer.open({
		title: title,
    	type: 1,
      	//skin: 'layui-layer-rim', //加上边框
      	skin: 'demo-class',
      	shade: false,
      	maxmin: true,
      	area: ['1200px', '600px'], //宽高
      	zIndex: layer.zIndex,
        success: function(layero){
        	// 置顶当前窗口 
            layer.setTop(layero);
        },
        moveEnd: function(layero){
        	// 置顶当前窗口 
            layer.setTop(layero);
        },
      	// content: '<textarea rows=27 style="width:100%;background:black;color:#fff" id="info"></textarea>',
      	content : '<div style="height:100%;background:black;color:#fff;border:#98bf21;overflow: auto;" id="' + divId + '" class="layui-field-box"></div>',
//      	cancel: function(index, layero) {
//      	  if ($('#wsDiv').text().search("脚本执行完成") != -1) {
//      		  return true;
//      	  }
//      		
//      	  if (confirm('安装过程无法中断，就算这个窗口关闭了后台也还在执行')){ //只有当点击confirm框的确定时，该层才会关闭
//      		  layer.close(index)
//      	  }
//      	  return false; 
//      	}    
    });
}

function makeGlobalTimerLayer(title, timerDivId, divId, hostId, logFilePath) {
	layer.open({
		title: title,
    	type: 1,
      	//skin: 'layui-layer-rim', //加上边框
      	skin: 'demo-class',
      	shade: false,
      	maxmin: true,
      	area: ['1200px', '600px'], //宽高
      	zIndex: layer.zIndex,
        success: function(layero){
        	// 置顶当前窗口 
            layer.setTop(layero);
        },
        moveEnd: function(layero){
        	// 置顶当前窗口 
            layer.setTop(layero);
        },
      	content : '<div style="height:100%;background:black;color:#fff;border:#98bf21;overflow: auto;" id="' + divId + '" class="layui-field-box"></div>',
      	cancel: function(index, layero) {
      		// 关闭timer
      		$('#' + timerDivId).timer('remove');
      		// 删除动态添加的timer的div
      		$('#' + timerDivId).remove();
      		
      		layer.close(index)
      	  return false; 
      	}    
    });
	
	// 动态插入timer
	var timerDivHtml = "<div id='" + timerDivId + "'></div>"; 
	$('#' + divId).append(timerDivHtml); 
	
	var curLine = 1;
	
	$('#' + timerDivId).timer({
		seconds: 2,	
		duration: '3s',
		repeat: true,	
		callback: function() {
			var url = CONTEXT_PATH + '/log/get';
	        
	        $.ajax({
	            url: url,
	            data: {logFilePath: logFilePath, hostId: hostId, curLine: curLine},
	        	success: function(result){
	        	    if(result.code == RESULT_FAIL){
	                    return;
	                } else {
	                	if (result.data.log != null && result.data.log != '') {
	                		var consoleDiv = $('#' + divId);
	                		consoleDiv.append(result.data.log + '<br>');
	                		
	                		// 滚动到最底
	                		consoleDiv.scrollTop(consoleDiv[0].scrollHeight);
		
	                		curLine = result.data.nextLine;
	                	}
	                }
	            }
	        });
		}
	});
}

function makeGlobalTimerLayer(title, timerDivId, divId, logFilePath) {
	layer.open({
		title: title,
    	type: 1,
      	//skin: 'layui-layer-rim', //加上边框
      	skin: 'demo-class',
      	shade: false,
      	maxmin: true,
      	area: ['1200px', '600px'], //宽高
      	zIndex: layer.zIndex,
        success: function(layero){
        	// 置顶当前窗口 
            layer.setTop(layero);
        },
        moveEnd: function(layero){
        	// 置顶当前窗口 
            layer.setTop(layero);
        },
      	content : '<div style="height:100%;background:black;color:#fff;border:#98bf21;overflow: auto;" id="' + divId + '" class="layui-field-box"></div>',
      	cancel: function(index, layero) {
      		// 关闭timer
      		$('#' + timerDivId).timer('remove');
      		// 删除动态添加的timer的div
      		$('#' + timerDivId).remove();
      		
      		layer.close(index)
      	  return false; 
      	}    
    });
	
	// 动态插入timer
	var timerDivHtml = "<div id='" + timerDivId + "'></div>"; 
	$('#' + divId).append(timerDivHtml); 
	
	var curLine = 1;
	
	$('#' + timerDivId).timer({
		seconds: 2,	
		duration: '3s',
		repeat: true,	
		callback: function() {
			var url = CONTEXT_PATH + '/log/getSelf';
	        
	        $.ajax({
	            url: url,
	            data: {logFilePath: logFilePath, curLine: curLine}, 
	        	success: function(result){
	        	    if(result.code == RESULT_FAIL){
	                    return;
	                } else {
	                	if (result.data.log != null && result.data.log != '') {
	                		var consoleDiv = $('#' + divId);
	                		consoleDiv.append(result.data.log + '<br>');
	                		
	                		// 滚动到最底
	                		consoleDiv.scrollTop(consoleDiv[0].scrollHeight);
		
	                		curLine = result.data.nextLine;
	                	}
	                }
	            } 
	        });
		}
	});
}

var new_conn = function() {
	var url = CONTEXT_PATH + "/wsHandler";
	var sock = new SockJS(url);
	
	// 连接建立成功后调用
	sock.onopen = function (ev) {
	 
	};
	
	// 收到消息调用
	sock.onmessage = function (ev) {
		// 找到iframe的websocket的回显div
		//var wsDiv = $('#main-content').contents().find('#wsDiv');

		// 解析json
		var resultJson = JSON.parse(ev.data);
		
		// 找到要回显的div
		var wsDiv = $('#' + resultJson.divId);
		
		var content = resultJson.content;
		
		if (wsDiv != null) {
			if (content == 'end') {
				return;
			}
			
			// 追加内容
			wsDiv.append(content + '<br>');
			
			// 滚动
			wsDiv.animate({scrollTop : wsDiv[0].scrollHeight}, '1000');
		}	 
	};
	
	sock.onclose = function (ev) {
	    console.log("closed");
	    // 过几秒后重连
        setTimeout(function() {
            new_conn();
        }, (Math.random() * 1 + 1 ) * 1000);   
	};
}

$(window).on('load', function() {
	// 登陆成功后就建立一条websocket
    new_conn();
	
	//执行选中导航栏
	(function selectActiveNav(){
		var index = _redirect_.indexOf('?');
		if(index!=-1){
			_redirect_ = _redirect_.substring(0,index);
		}
		var $_redirect = $('[data-link="'+_redirect_+'"]');
		if($_redirect){
			$_redirect.addClass('active');//自己
			if($_redirect.hasClass('nav-level2')){//如果是二级需要再选中一级
				$_redirect.closest('.nav-level1').addClass('active');
			}
		}
	})();
	var index = undefined;
	
	//上导航事件
	$('.nav-item').on('click',function(){
		
		var $this = $(this);
		var link = $this.attr('data-link');
		
		var $navbar_group = $this.closest('.navbar-group');
		var data_target = $this.attr('data-target');
		if('window'===data_target){//新开窗口
			location.href=link;
			return;
		}
		if(link){
			var productId = $('.navbar_item_game').find('li.active').attr('data-id');
			index = layer.load(1, {shade:[0.1,'#fff']});
			$('#main-content').attr('src',link+'?productId='+productId);
			
			if($this.hasClass('nav-level1')){
				$navbar_group.find('.nav-level1').removeClass('active');
				$navbar_group.find('.nav-level1 .nav-level2.active').removeClass('active');
			}else if($this.hasClass('nav-level2')){
				$navbar_group.find('.nav-level2').removeClass('active');
				var $parent = $navbar_group.closest('.nav-level1');
				$parent.siblings('.nav-level1').removeClass('active');
				$parent.parent().find('.nav-level1 .active').removeClass('active');
				$parent.addClass('active');
				$navbar_group.addClass('active');
			}
			$this.addClass('active');
		}
		
	});
	
	//二级菜单
	$('.nav-level1').hover(function(){
			var $this = $(this);
			var $group = $this.find('.nav-level2-group');
			$group.show();
		},
		function(){
			var $this = $(this);
			var $group = $this.find('.nav-level2-group');
			$group.hide();
		}
	);
	
	
	//内容 iframe  加载提示
	var $iframe = $('#main-content');
	$iframe.load(function(){ 
		if(index){
			layer.close(index);
		}
		index = undefined;
	});     
	
	
	$('.navbar_item_game').on('click',function(){
		var _$this = $(this);
		if(_$this.hasClass('spread')){
			_$this.removeClass('spread');
			_$this.find('.navbar-group').hide();
		}else{
			_$this.addClass('spread');
			_$this.find('.navbar-group').show();
		}
	});
	
	$('#game_selece_ul>li').on('click',function(){
		$('#game_selece_ul>li').removeClass('active');
		var _$this = $(this);
		_$this.addClass('active');
        var productId = _$this.attr('data-id');
		var title = _$this.find('.navbar-item-title').text();
		var curName = $('#game_name').text();
		$('#game_name').text(title);
		
		if(curName!=title){//切换
			var $content_iframe = $('#main-content');
			var curPage = $content_iframe.attr('src');
			//$.reloadContentIframe(curPage);
			reloadWindow(productId);
		}
		
	});

	function reloadWindow(productId){
        var src = $('.navbar-nav.navbar-left.navbar-group').find('.active').last().attr('data-link');
        var params = {productId:productId};
        if(src){
            params['redirect'] = src;
        }
        postcall( CONTEXT_PATH + '/',params);
	}

	
	//强制刷新内容Iframe
	function reloadContentIframe(src){
		var $content_iframe = $('#main-content');
		$content_iframe.attr('src',src);
	}
	
	//把刷新方法给到jquery全局中，在其他地方可以直接强制刷新
	$.reloadContentIframe = reloadContentIframe;

});

